/**
 * 
 */
package com.demo2do.strawberry.security;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.demo2do.strawberry.entity.user.UserRegister;
import com.demo2do.strawberry.entity.user.profile.Profile;
import com.demo2do.strawberry.service.UserService;

/**
 * @author Downpour
 */
public class StrawberryAuthenticationProvider implements UserDetailsService {
	
	private static final Log logger = LogFactory.getLog(StrawberryAuthenticationProvider.class);
	
	@Autowired
	private UserService userService;
	
	/* (non-Javadoc)
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */
	public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
		
		List<UserRegister> userRegisters = userService.getUserRegister(username, false);
		
		if(userRegisters.isEmpty()) {
			throw new UsernameNotFoundException("user " + username + " is not found");
		}
		
		UserRegister userRegister = userRegisters.get(0);
			
		if (!userRegister.isEnabled()) {
			throw new LockedException("security.authentication.locked");
		}

		logger.info(username + " - " + userRegister.getAuthorities() + " is found to login. ");
		
		// initialize userProfile
		Profile profile = userService.getUserProfile(userRegister.getMember());
		
		userRegister.initialize(profile);
		
		return userRegister;
	}

}
